package com.feng.seata.config;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Slf4j
public class SnowflakeGenerator {

    //   id format  =>
    //   timestamp | worker | dataCenter | sequence
    //   41        |    5   |      5     |  12
    private final long sequenceBits = 12;
    private final long dataCenterIdBits = 5L;
    private final long workerIdBits = 5L;
    private final long maxDataCenterId = ~(-1L << dataCenterIdBits);
    private final long maxWorkerId = ~(-1L << workerIdBits);


    private final long workerIdShift = sequenceBits;
    private final long dataCenterIdShift = sequenceBits + workerIdBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;

    // 2017-04-04 00:00:00
    private final long twEpoch = LocalDateTime.of(2021, 07, 01, 0, 0, 0, 0)
            .toInstant(ZoneOffset.UTC).toEpochMilli();
    private final long dataCenterId;
    private final long workerId;
    private final long sequenceMax = ~(-1L << sequenceBits);

    private volatile long lastTimestamp = -1L;
    private volatile long sequence = 0L;

    public SnowflakeGenerator(long dataCenterId, long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", workerId));
        }
        if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
        }
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
        log.info("init snowflake, dataCenterId: {}, workerId: {}", dataCenterId, workerId);
    }

    public synchronized Long generateLongId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id for " + (
                    lastTimestamp - timestamp) + " milliseconds.");
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) % sequenceMax;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        lastTimestamp = timestamp;
        return ((timestamp - twEpoch) << timestampLeftShift) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    public synchronized String generateId() {
        return String.valueOf(generateLongId());
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}

